package co.baiku.boot.config;

import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

@Configuration
public class SchedulerQuartzConfig {
    @Resource
    private SchedulerQuartzJob schedulerQuartzJob;
    @Resource
    private DataSource druid;


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        //获取配置属性
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
        //在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        //创建SchedulerFactoryBean
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        Properties pro = propertiesFactoryBean.getObject();
        factory.setOverwriteExistingJobs(true);
        factory.setDataSource(druid);

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        if (pro != null) {
            executor.setCorePoolSize(Integer.valueOf(pro.getOrDefault("corePoolSize", 10).toString()));
            executor.setMaxPoolSize(Integer.valueOf(pro.getOrDefault("maxPoolSize", 20).toString()));
            executor.setQueueCapacity(Integer.valueOf(pro.getOrDefault("queueCapacity", 100).toString()));
        } else {
            throw new IOException("未找到文件:quartz.properties");
        }

        factory.setTaskExecutor(executor);
        factory.setAutoStartup(true);
        factory.setQuartzProperties(pro);
        factory.setJobFactory(schedulerQuartzJob);
        return factory;
    }

}